<!DOCTYPE html>
<html lang="">
    <head><meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script><meta name='description' content='一、模式简介 观察者模式是《Headfirst 设计模式》中讲的第二个设计模式，并且在java中也是应用的非常广泛，可见其重要性。观察者模式：是一种行为设计模式， 它定义了对象之间一对多的机制，通过订阅方式，可在对象事件发生时通知多个 “观察” 该对象的其他对象。 生活中联想到很多这种机制的事情，比如：我在报社订阅了报纸，报社就会定期的为我推送报纸或者在微信上我订阅了一个公众号，当公众号会为我推送新内容，观察者模式就是基于这种发布订阅模式的设计模式。下面我会对模式的含义和应用场景进行详细的说明。
二、模式详解 ​	下面有这样一个场景我们要实现一个气象站系统，此系统是由三部分去构成，第一部分：气象站，它可以通过检测的仪器去获得湿度、温度、气压。第二部分WeatherData对象，气象传感发布装置，获取到数据后发布出去。第三部分：布告板，用于展示所获得的数据。现在想要当气象站拥有新的检测数据时，实时的通过气象传感装置去更新布告板。
 
从图中我们可以看到WetherData对象获取到数据后，就会更新布告板。那么我们可不可以这样进行操作呢？ 
对于这种实现，不难看出是非常冗余的，这种实现的缺点有：
  我们针对具体的实现编程，而非针对接口。
  对于每个新布告板，我们都得改变一下代码。
  我们无法在运行时动态的增加（删除）布告板。
  我们尚未封装改变的部分。
  因此我们需要引入观察者模式来解决这一问题。布告板（观察者）、气象发布装置（被观察者，也称主题）当被观察者有了新的数据后，就可以实时的去发布通知给被观察者，并且观察者可以通过向主题注册和移除来动态的去接收数据，从而解决上述问题达到松耦合的效果。
 
通过这样的结构可以知道观察者不需要知道主题的内部细节只需要实现Observer接口，就可以更新我们自己的状态，并且还可以动态的注册剔除观察者，这更加符合了迪米特法则和开闭原则。
三、代码示例 ​	在java中已经内置了观察者模式java.util包中包含了Observer接口与Observerable类，等同于我们前面提到过的Observer接口和Subject接口。并且提供了”推“和&amp;quot;拉&amp;quot;的方式提供数据。下面我们先来自己实现一套观察者模式，在来实现java内置的观察者模式。
自定义   主题接口
/** * 主题 * */ public interface Subject { /** * 注册观察者 */ void registerObserver(Observer observer); /** * 删除观察者 */ void removeObserver(Observer observer); /** * 通知观察者 */ void notifyObservers(); }   观察者接口'><title>设计模式-观察者模式</title>

<link rel='canonical' href='http://example.org/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/'>

<link rel="stylesheet" href="/scss/style.min.css"><meta property='og:title' content='设计模式-观察者模式'>
<meta property='og:description' content='一、模式简介 观察者模式是《Headfirst 设计模式》中讲的第二个设计模式，并且在java中也是应用的非常广泛，可见其重要性。观察者模式：是一种行为设计模式， 它定义了对象之间一对多的机制，通过订阅方式，可在对象事件发生时通知多个 “观察” 该对象的其他对象。 生活中联想到很多这种机制的事情，比如：我在报社订阅了报纸，报社就会定期的为我推送报纸或者在微信上我订阅了一个公众号，当公众号会为我推送新内容，观察者模式就是基于这种发布订阅模式的设计模式。下面我会对模式的含义和应用场景进行详细的说明。
二、模式详解 ​	下面有这样一个场景我们要实现一个气象站系统，此系统是由三部分去构成，第一部分：气象站，它可以通过检测的仪器去获得湿度、温度、气压。第二部分WeatherData对象，气象传感发布装置，获取到数据后发布出去。第三部分：布告板，用于展示所获得的数据。现在想要当气象站拥有新的检测数据时，实时的通过气象传感装置去更新布告板。
 
从图中我们可以看到WetherData对象获取到数据后，就会更新布告板。那么我们可不可以这样进行操作呢？ 
对于这种实现，不难看出是非常冗余的，这种实现的缺点有：
  我们针对具体的实现编程，而非针对接口。
  对于每个新布告板，我们都得改变一下代码。
  我们无法在运行时动态的增加（删除）布告板。
  我们尚未封装改变的部分。
  因此我们需要引入观察者模式来解决这一问题。布告板（观察者）、气象发布装置（被观察者，也称主题）当被观察者有了新的数据后，就可以实时的去发布通知给被观察者，并且观察者可以通过向主题注册和移除来动态的去接收数据，从而解决上述问题达到松耦合的效果。
 
通过这样的结构可以知道观察者不需要知道主题的内部细节只需要实现Observer接口，就可以更新我们自己的状态，并且还可以动态的注册剔除观察者，这更加符合了迪米特法则和开闭原则。
三、代码示例 ​	在java中已经内置了观察者模式java.util包中包含了Observer接口与Observerable类，等同于我们前面提到过的Observer接口和Subject接口。并且提供了”推“和&amp;quot;拉&amp;quot;的方式提供数据。下面我们先来自己实现一套观察者模式，在来实现java内置的观察者模式。
自定义   主题接口
/** * 主题 * */ public interface Subject { /** * 注册观察者 */ void registerObserver(Observer observer); /** * 删除观察者 */ void removeObserver(Observer observer); /** * 通知观察者 */ void notifyObservers(); }   观察者接口'>
<meta property='og:url' content='http://example.org/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/'>
<meta property='og:site_name' content='我的技术小屋'>
<meta property='og:type' content='article'><meta property='article:section' content='Post' /><meta property='article:tag' content='设计模式' /><meta property='article:published_time' content='2022-01-26T00:00:00&#43;00:00'/><meta property='article:modified_time' content='2022-01-26T00:00:00&#43;00:00'/><meta property='og:image' content='http://example.org/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1.jfif' />
<meta name="twitter:title" content="设计模式-观察者模式">
<meta name="twitter:description" content="一、模式简介 观察者模式是《Headfirst 设计模式》中讲的第二个设计模式，并且在java中也是应用的非常广泛，可见其重要性。观察者模式：是一种行为设计模式， 它定义了对象之间一对多的机制，通过订阅方式，可在对象事件发生时通知多个 “观察” 该对象的其他对象。 生活中联想到很多这种机制的事情，比如：我在报社订阅了报纸，报社就会定期的为我推送报纸或者在微信上我订阅了一个公众号，当公众号会为我推送新内容，观察者模式就是基于这种发布订阅模式的设计模式。下面我会对模式的含义和应用场景进行详细的说明。
二、模式详解 ​	下面有这样一个场景我们要实现一个气象站系统，此系统是由三部分去构成，第一部分：气象站，它可以通过检测的仪器去获得湿度、温度、气压。第二部分WeatherData对象，气象传感发布装置，获取到数据后发布出去。第三部分：布告板，用于展示所获得的数据。现在想要当气象站拥有新的检测数据时，实时的通过气象传感装置去更新布告板。
 
从图中我们可以看到WetherData对象获取到数据后，就会更新布告板。那么我们可不可以这样进行操作呢？ 
对于这种实现，不难看出是非常冗余的，这种实现的缺点有：
  我们针对具体的实现编程，而非针对接口。
  对于每个新布告板，我们都得改变一下代码。
  我们无法在运行时动态的增加（删除）布告板。
  我们尚未封装改变的部分。
  因此我们需要引入观察者模式来解决这一问题。布告板（观察者）、气象发布装置（被观察者，也称主题）当被观察者有了新的数据后，就可以实时的去发布通知给被观察者，并且观察者可以通过向主题注册和移除来动态的去接收数据，从而解决上述问题达到松耦合的效果。
 
通过这样的结构可以知道观察者不需要知道主题的内部细节只需要实现Observer接口，就可以更新我们自己的状态，并且还可以动态的注册剔除观察者，这更加符合了迪米特法则和开闭原则。
三、代码示例 ​	在java中已经内置了观察者模式java.util包中包含了Observer接口与Observerable类，等同于我们前面提到过的Observer接口和Subject接口。并且提供了”推“和&amp;quot;拉&amp;quot;的方式提供数据。下面我们先来自己实现一套观察者模式，在来实现java内置的观察者模式。
自定义   主题接口
/** * 主题 * */ public interface Subject { /** * 注册观察者 */ void registerObserver(Observer observer); /** * 删除观察者 */ void removeObserver(Observer observer); /** * 通知观察者 */ void notifyObservers(); }   观察者接口"><meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:image" content='http://example.org/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1.jfif' />
    <link rel="shortcut icon" href="/img/%e7%bc%85%e5%9b%a0%e7%8c%ab.png" />
<style>
    :root {
        --article-font-family: "Noto Serif SC", var(--base-font-family);
    }
</style>

<script> 
		(function () {
		    const customFont = document.createElement('link');
		    customFont.href = "https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@300;700&display=swap"; 
		    customFont.type = "text/css";
		    customFont.rel = "stylesheet";
		
		    document.head.appendChild(customFont);
		}());
</script>
    </head>
    <body class="
    article-page has-toc
">
    <script>
        (function() {
            const colorSchemeKey = 'StackColorScheme';
            if(!localStorage.getItem(colorSchemeKey)){
                localStorage.setItem(colorSchemeKey, "auto");
            }
        })();
    </script><script>
    (function() {
        const colorSchemeKey = 'StackColorScheme';
        const colorSchemeItem = localStorage.getItem(colorSchemeKey);
        const supportDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches === true;

        if (colorSchemeItem == 'dark' || colorSchemeItem === 'auto' && supportDarkMode) {
            

            document.documentElement.dataset.scheme = 'dark';
        } else {
            document.documentElement.dataset.scheme = 'light';
        }
    })();
</script>
<div class="container main-container flex 
    
        extended
    
">
    
        <div id="article-toolbar">
            <a href="/" class="back-home">
                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-chevron-left" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <polyline points="15 6 9 12 15 18" />
</svg>



                <span>Back</span>
            </a>
        </div>
    
<main class="main full-width">
    <article class="has-image main-article">
    <header class="article-header">
        <div class="article-image">
            <a href="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/">
                <img src="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1_hu6c0eed8e37f4c0026f67918d61df758e_74484_800x0_resize_q75_box.jfif"
                        srcset="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1_hu6c0eed8e37f4c0026f67918d61df758e_74484_800x0_resize_q75_box.jfif 800w, /post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1_hu6c0eed8e37f4c0026f67918d61df758e_74484_1600x0_resize_q75_box.jfif 1600w"
                        width="800" 
                        height="450" 
                        loading="lazy"
                        alt="Featured image of post 设计模式-观察者模式" />
                
            </a>
        </div>
    

    <div class="article-details">
    
    <header class="article-category">
        
            <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" >
                设计模式
            </a>
        
    </header>
    

    <h2 class="article-title">
        <a href="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/">设计模式-观察者模式</a>
    </h2>

    

    
    <footer class="article-time">
        
            <div>
                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-calendar-time" width="56" height="56" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <path d="M11.795 21h-6.795a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v4" />
  <circle cx="18" cy="18" r="4" />
  <path d="M15 3v4" />
  <path d="M7 3v4" />
  <path d="M3 11h16" />
  <path d="M18 16.496v1.504l1 1" />
</svg>
                <time class="article-time--published">Jan 26, 2022</time>
            </div>
        

        
            <div>
                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <circle cx="12" cy="12" r="9" />
  <polyline points="12 7 12 12 15 15" />
</svg>



                <time class="article-time--reading">
                    3 minute read
                </time>
            </div>
        
    </footer>
    
</div>
</header>

    <section class="article-content">
    <h2 id="一模式简介">一、模式简介</h2>
<p>观察者模式是《Headfirst 设计模式》中讲的第二个设计模式，并且在java中也是应用的非常广泛，可见其重要性。<strong>观察者模式：是一种行为设计模式， 它定义了对象之间一对多的机制，通过订阅方式，可在对象事件发生时通知多个 “观察” 该对象的其他对象。</strong>
生活中联想到很多这种机制的事情，比如：我在报社订阅了报纸，报社就会定期的为我推送报纸或者在微信上我订阅了一个公众号，当公众号会为我推送新内容，观察者模式就是基于这种发布订阅模式的设计模式。下面我会对模式的含义和应用场景进行详细的说明。</p>
<h2 id="二模式详解">二、模式详解</h2>
<p>​	下面有这样一个场景我们要实现一个气象站系统，此系统是由三部分去构成，第一部分：气象站，它可以通过检测的仪器去获得湿度、温度、气压。第二部分WeatherData对象，气象传感发布装置，获取到数据后发布出去。第三部分：布告板，用于展示所获得的数据。现在想要当气象站拥有新的检测数据时，实时的通过气象传感装置去更新布告板。</p>
<p><figure 
	
		class="gallery-image" 
		style="
			flex-grow: 335; 
			flex-basis: 804px"
	>
	<a href="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85.png" data-size="892x266">
		<img src="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85.png"
			width="892"
			height="266"
			srcset="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85_hu3d4f0a74e0772dafca24cfc9ec9690c7_32028_480x0_resize_box_3.png 480w, /post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85_hu3d4f0a74e0772dafca24cfc9ec9690c7_32028_1024x0_resize_box_3.png 1024w"
			loading="lazy"
			>
	</a>
	
</figure></p>
<p>从图中我们可以看到WetherData对象获取到数据后，就会更新布告板。那么我们可不可以这样进行操作呢？<figure 
	
		class="gallery-image" 
		style="
			flex-grow: 320; 
			flex-basis: 770px"
	>
	<a href="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E6%B0%94%E5%8E%8B.png" data-size="799x249">
		<img src="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E6%B0%94%E5%8E%8B.png"
			width="799"
			height="249"
			srcset="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E6%B0%94%E5%8E%8B_hu2162e6c314dac9a529b1324fac54ec4d_10290_480x0_resize_box_3.png 480w, /post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E6%B0%94%E5%8E%8B_hu2162e6c314dac9a529b1324fac54ec4d_10290_1024x0_resize_box_3.png 1024w"
			loading="lazy"
			>
	</a>
	
</figure></p>
<p>对于这种实现，不难看出是非常冗余的，这种实现的缺点有：</p>
<ul>
<li>
<p>我们针对具体的实现编程，而非针对接口。</p>
</li>
<li>
<p>对于每个新布告板，我们都得改变一下代码。</p>
</li>
<li>
<p>我们无法在运行时动态的增加（删除）布告板。</p>
</li>
<li>
<p>我们尚未封装改变的部分。</p>
</li>
</ul>
<p>因此我们需要引入观察者模式来解决这一问题。布告板（观察者）、气象发布装置（被观察者，也称主题）当被观察者有了新的数据后，就可以实时的去发布通知给被观察者，并且观察者可以通过向主题注册和移除来动态的去接收数据，从而解决上述问题达到松耦合的效果。</p>
<p><figure 
	
		class="gallery-image" 
		style="
			flex-grow: 165; 
			flex-basis: 397px"
	>
	<a href="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%A7%82%E5%AF%9F.png" data-size="1055x637">
		<img src="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%A7%82%E5%AF%9F.png"
			width="1055"
			height="637"
			srcset="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%A7%82%E5%AF%9F_huef7d94b7b2a54fd9e52e74ac3e135c32_89948_480x0_resize_box_3.png 480w, /post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%A7%82%E5%AF%9F_huef7d94b7b2a54fd9e52e74ac3e135c32_89948_1024x0_resize_box_3.png 1024w"
			loading="lazy"
			>
	</a>
	
</figure></p>
<p>通过这样的结构可以知道观察者不需要知道主题的内部细节只需要实现Observer接口，就可以更新我们自己的状态，并且还可以动态的注册剔除观察者，这更加符合了<strong>迪米特法则</strong>和<strong>开闭原则</strong>。</p>
<h2 id="三代码示例">三、代码示例</h2>
<p>​	在java中已经内置了观察者模式java.util包中包含了Observer接口与Observerable类，等同于我们前面提到过的Observer接口和Subject接口。并且提供了”推“和&quot;拉&quot;的方式提供数据。下面我们先来自己实现一套观察者模式，在来实现java内置的观察者模式。</p>
<h3 id="自定义">自定义</h3>
<ul>
<li>
<p>主题接口</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#75715e">/**
</span><span style="color:#75715e"> * 主题
</span><span style="color:#75715e"> *
</span><span style="color:#75715e"> */</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Subject</span> <span style="color:#f92672">{</span>

    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 注册观察者
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">registerObserver</span><span style="color:#f92672">(</span>Observer observer<span style="color:#f92672">);</span>

    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 删除观察者
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">removeObserver</span><span style="color:#f92672">(</span>Observer observer<span style="color:#f92672">);</span>

    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 通知观察者
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">notifyObservers</span><span style="color:#f92672">();</span>
<span style="color:#f92672">}</span>
</code></pre></div></li>
<li>
<p>观察者接口</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#75715e">/**
</span><span style="color:#75715e"> * 观察者
</span><span style="color:#75715e"> *
</span><span style="color:#75715e"> */</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">Observer</span> <span style="color:#f92672">{</span>

    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 更新
</span><span style="color:#75715e">     *
</span><span style="color:#75715e">     * @param temp     温度
</span><span style="color:#75715e">     * @param humidity 湿度
</span><span style="color:#75715e">     * @param pressure 压力
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">update</span><span style="color:#f92672">(</span><span style="color:#66d9ef">float</span> temp<span style="color:#f92672">,</span><span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">,</span><span style="color:#66d9ef">float</span> pressure<span style="color:#f92672">);</span>

<span style="color:#f92672">}</span>
</code></pre></div></li>
<li>
<p>布告板展示接口（把变化部分抽出来）</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#75715e">/**
</span><span style="color:#75715e"> * 布告板展示
</span><span style="color:#75715e"> *
</span><span style="color:#75715e"> */</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">DisplayElement</span> <span style="color:#f92672">{</span>
    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 显示
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">display</span><span style="color:#f92672">();</span>
<span style="color:#f92672">}</span>
</code></pre></div></li>
<li>
<p>WeatherData（主题对象）</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#75715e">/**
</span><span style="color:#75715e"> * 天气数据
</span><span style="color:#75715e"> *
</span><span style="color:#75715e"> */</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">WeatherData</span> <span style="color:#66d9ef">implements</span> Subject <span style="color:#f92672">{</span>

    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 存放观察者集合
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">private</span> ArrayList observers<span style="color:#f92672">;</span>
    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 温度
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> temperature<span style="color:#f92672">;</span>
    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 湿度
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">;</span>
    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 压力
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> pressure<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">WeatherData</span><span style="color:#f92672">(){</span>
        <span style="color:#75715e">//初始化观察者集合
</span><span style="color:#75715e"></span>        observers<span style="color:#f92672">=</span><span style="color:#66d9ef">new</span> ArrayList<span style="color:#f92672">&lt;&gt;();</span>
    <span style="color:#f92672">}</span>
    <span style="color:#a6e22e">@Override</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">registerObserver</span><span style="color:#f92672">(</span>Observer observer<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
    observers<span style="color:#f92672">.</span><span style="color:#a6e22e">add</span><span style="color:#f92672">(</span>observer<span style="color:#f92672">);</span>
    <span style="color:#f92672">}</span>

    <span style="color:#a6e22e">@Override</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">removeObserver</span><span style="color:#f92672">(</span>Observer observer<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
        <span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> observers<span style="color:#f92672">.</span><span style="color:#a6e22e">indexOf</span><span style="color:#f92672">(</span>observer<span style="color:#f92672">);</span>
        <span style="color:#66d9ef">if</span> <span style="color:#f92672">(</span>i<span style="color:#f92672">&gt;=</span>0<span style="color:#f92672">){</span>
            observers<span style="color:#f92672">.</span><span style="color:#a6e22e">remove</span><span style="color:#f92672">(</span>i<span style="color:#f92672">);</span>
        <span style="color:#f92672">}</span>
    <span style="color:#f92672">}</span>

    <span style="color:#a6e22e">@Override</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">notifyObservers</span><span style="color:#f92672">()</span> <span style="color:#f92672">{</span>
        <span style="color:#66d9ef">for</span> <span style="color:#f92672">(</span><span style="color:#66d9ef">int</span> i <span style="color:#f92672">=</span> 0<span style="color:#f92672">;</span> i <span style="color:#f92672">&lt;</span> observers<span style="color:#f92672">.</span><span style="color:#a6e22e">size</span><span style="color:#f92672">();</span> i<span style="color:#f92672">++)</span> <span style="color:#f92672">{</span>
            Observer o <span style="color:#f92672">=</span> <span style="color:#f92672">(</span>Observer<span style="color:#f92672">)</span> observers<span style="color:#f92672">.</span><span style="color:#a6e22e">get</span><span style="color:#f92672">(</span>i<span style="color:#f92672">);</span>
            o<span style="color:#f92672">.</span><span style="color:#a6e22e">update</span><span style="color:#f92672">(</span>temperature<span style="color:#f92672">,</span>humidity<span style="color:#f92672">,</span>pressure<span style="color:#f92672">);</span>
        <span style="color:#f92672">}</span>
    <span style="color:#f92672">}</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">measurementsChanged</span><span style="color:#f92672">(){</span>
        notifyObservers<span style="color:#f92672">();</span>
    <span style="color:#f92672">}</span>

    <span style="color:#75715e">//当从气象站获取到新的值我们可以通知观察者们，采用推的方式
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">setMeasurements</span><span style="color:#f92672">(</span><span style="color:#66d9ef">float</span> temperature<span style="color:#f92672">,</span><span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">,</span><span style="color:#66d9ef">float</span> pressure<span style="color:#f92672">){</span>
    <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">temperature</span><span style="color:#f92672">=</span>temperature<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">humidity</span><span style="color:#f92672">=</span>humidity<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">pressure</span><span style="color:#f92672">=</span>pressure<span style="color:#f92672">;</span>
    measurementsChanged<span style="color:#f92672">();</span>
    <span style="color:#f92672">}</span>
<span style="color:#f92672">}</span>
</code></pre></div></li>
<li>
<p>布告板（观察者对象）</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#75715e">/**
</span><span style="color:#75715e"> * 布告板(观察者)
</span><span style="color:#75715e"> *
</span><span style="color:#75715e"> */</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CurrentConditionsDisplay</span> <span style="color:#66d9ef">implements</span> Observer<span style="color:#f92672">,</span> DisplayElement <span style="color:#f92672">{</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> temperature<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">private</span> Subject weatherData<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">public</span>  <span style="color:#a6e22e">CurrentConditionsDisplay</span><span style="color:#f92672">(</span>Subject weatherData<span style="color:#f92672">){</span>
        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">weatherData</span><span style="color:#f92672">=</span>weatherData<span style="color:#f92672">;</span>
        <span style="color:#75715e">//在构造方法中将自己注册进去
</span><span style="color:#75715e"></span>      weatherData<span style="color:#f92672">.</span><span style="color:#a6e22e">registerObserver</span><span style="color:#f92672">(</span><span style="color:#66d9ef">this</span><span style="color:#f92672">);</span>
    <span style="color:#f92672">}</span>
    <span style="color:#a6e22e">@Override</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">update</span><span style="color:#f92672">(</span><span style="color:#66d9ef">float</span> temp<span style="color:#f92672">,</span> <span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">,</span> <span style="color:#66d9ef">float</span> pressure<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">temperature</span><span style="color:#f92672">=</span>temp<span style="color:#f92672">;</span>
        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">humidity</span><span style="color:#f92672">=</span>humidity<span style="color:#f92672">;</span>
        display<span style="color:#f92672">();</span>
    <span style="color:#f92672">}</span>
    <span style="color:#a6e22e">@Override</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">display</span><span style="color:#f92672">()</span> <span style="color:#f92672">{</span>
        System<span style="color:#f92672">.</span><span style="color:#a6e22e">out</span><span style="color:#f92672">.</span><span style="color:#a6e22e">println</span><span style="color:#f92672">(</span><span style="color:#e6db74">&#34;Current Conditions:&#34;</span><span style="color:#f92672">+</span>temperature<span style="color:#f92672">+</span><span style="color:#e6db74">&#34;F degress and&#34;</span><span style="color:#f92672">+</span>humidity<span style="color:#f92672">+</span><span style="color:#e6db74">&#34;% humidity&#34;</span><span style="color:#f92672">);</span>
    <span style="color:#f92672">}</span>
<span style="color:#f92672">}</span>
</code></pre></div></li>
</ul>
<h3 id="java内置">java内置</h3>
<p>本次我们以拉取的形式，更新数据。</p>
<ul>
<li>WeatherData（主题对象）</li>
</ul>
<p>​	因部分方法已经被Observerable类实现好，我们只需要继承java.util.Observerable类</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#75715e">/**
</span><span style="color:#75715e"> * 天气数据
</span><span style="color:#75715e"> *
</span><span style="color:#75715e"> */</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">WeatherData</span> <span style="color:#66d9ef">extends</span> Observable <span style="color:#f92672">{</span>

    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 温度
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> temperature<span style="color:#f92672">;</span>
    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 湿度
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">;</span>
    <span style="color:#75715e">/**
</span><span style="color:#75715e">     * 压力
</span><span style="color:#75715e">     */</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> pressure<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">public</span> <span style="color:#a6e22e">WeatherData</span><span style="color:#f92672">(){</span>

    <span style="color:#f92672">}</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">measurementsChanged</span><span style="color:#f92672">(){</span>
        setChanged<span style="color:#f92672">();</span>
        notifyObservers<span style="color:#f92672">();</span>
    <span style="color:#f92672">}</span>
    <span style="color:#75715e">//当从气象站获取到新的值我们可以通知观察者们
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">setMeasurements</span><span style="color:#f92672">(</span><span style="color:#66d9ef">float</span> temperature<span style="color:#f92672">,</span><span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">,</span><span style="color:#66d9ef">float</span> pressure<span style="color:#f92672">){</span>
    <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">temperature</span><span style="color:#f92672">=</span>temperature<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">humidity</span><span style="color:#f92672">=</span>humidity<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">pressure</span><span style="color:#f92672">=</span>pressure<span style="color:#f92672">;</span>
    measurementsChanged<span style="color:#f92672">();</span>
    <span style="color:#f92672">}</span>
    <span style="color:#75715e">//这些方法是为了让观察者们以拉的方式去获取到数据
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">float</span> <span style="color:#a6e22e">getTemperature</span><span style="color:#f92672">(){</span>
        <span style="color:#66d9ef">return</span> temperature<span style="color:#f92672">;</span>
    <span style="color:#f92672">}</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">float</span> <span style="color:#a6e22e">getHumidity</span><span style="color:#f92672">(){</span>
        <span style="color:#66d9ef">return</span> humidity<span style="color:#f92672">;</span>
    <span style="color:#f92672">}</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">float</span> <span style="color:#a6e22e">getPressure</span><span style="color:#f92672">(){</span>
        <span style="color:#66d9ef">return</span> pressure<span style="color:#f92672">;</span>
    <span style="color:#f92672">}</span>
<span style="color:#f92672">}</span>
</code></pre></div><p>setchanged方法，是为了让主题控制是否发布。</p>
<ul>
<li>布告板（观察者）</li>
</ul>
<p>java提供了Observer接口，我们只需实现java.util.Observer接口。</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#f92672">import</span> java.util.Observable<span style="color:#f92672">;</span>
<span style="color:#f92672">import</span> java.util.Observer<span style="color:#f92672">;</span>

<span style="color:#75715e">/**
</span><span style="color:#75715e"> * 布告板(观察者)
</span><span style="color:#75715e"> *
</span><span style="color:#75715e"> */</span>
<span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">CurrentConditionsDisplay</span> <span style="color:#66d9ef">implements</span> Observer<span style="color:#f92672">,</span> DisplayElement <span style="color:#f92672">{</span>

    <span style="color:#66d9ef">private</span> Observable observable<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> temperature<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">float</span> humidity<span style="color:#f92672">;</span>
    <span style="color:#66d9ef">public</span>  <span style="color:#a6e22e">CurrentConditionsDisplay</span><span style="color:#f92672">(</span>Observable weatherData<span style="color:#f92672">){</span>
        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">observable</span><span style="color:#f92672">=</span>weatherData<span style="color:#f92672">;</span>
        <span style="color:#75715e">//在构造方法中将自己注册进去
</span><span style="color:#75715e"></span>        observable<span style="color:#f92672">.</span><span style="color:#a6e22e">addObserver</span><span style="color:#f92672">(</span><span style="color:#66d9ef">this</span><span style="color:#f92672">);</span>
    <span style="color:#f92672">}</span>
    <span style="color:#a6e22e">@Override</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">display</span><span style="color:#f92672">()</span> <span style="color:#f92672">{</span>
        System<span style="color:#f92672">.</span><span style="color:#a6e22e">out</span><span style="color:#f92672">.</span><span style="color:#a6e22e">println</span><span style="color:#f92672">(</span><span style="color:#e6db74">&#34;Current Conditions:&#34;</span><span style="color:#f92672">+</span>temperature<span style="color:#f92672">+</span><span style="color:#e6db74">&#34;F degress and&#34;</span><span style="color:#f92672">+</span>humidity<span style="color:#f92672">+</span><span style="color:#e6db74">&#34;% humidity&#34;</span><span style="color:#f92672">);</span>
    <span style="color:#f92672">}</span>

    <span style="color:#a6e22e">@Override</span>
    <span style="color:#75715e">//参数o weatherData对象,arg数据流对象
</span><span style="color:#75715e"></span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">update</span><span style="color:#f92672">(</span>Observable o<span style="color:#f92672">,</span> Object arg<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
    <span style="color:#66d9ef">if</span> <span style="color:#f92672">(</span>o <span style="color:#66d9ef">instanceof</span> WeatherData<span style="color:#f92672">){</span>
        WeatherData weatherData<span style="color:#f92672">=</span> <span style="color:#f92672">(</span>WeatherData<span style="color:#f92672">)</span> o<span style="color:#f92672">;</span>
        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">temperature</span><span style="color:#f92672">=</span> weatherData<span style="color:#f92672">.</span><span style="color:#a6e22e">getTemperature</span><span style="color:#f92672">();</span>
        <span style="color:#66d9ef">this</span><span style="color:#f92672">.</span><span style="color:#a6e22e">humidity</span><span style="color:#f92672">=</span>weatherData<span style="color:#f92672">.</span><span style="color:#a6e22e">getHumidity</span><span style="color:#f92672">();</span>
        display<span style="color:#f92672">();</span>
    <span style="color:#f92672">}</span>
    <span style="color:#f92672">}</span>
<span style="color:#f92672">}</span>
</code></pre></div><p>我门可以看到主题是继承自Observable类来实现的，其实它是有一些缺点的，因为Observerable是<strong>无法序列化</strong>的所以会出现一些bug，而且方法可以被其子类覆盖，并且事件通知可以以不同的顺序并且可能在不同的线程上发生，这足以破坏任何<strong>线程安全性</strong>。在jdk9以后已被弃用。</p>
<h3 id="代码示例总结">代码示例总结</h3>
<p>通过上述两种方式实现观察者模式，自定义的方式更加的灵活一些，java内置的观察者在通知观察者时会改变通知的顺序并存在序列化的bug，大家可以创建多个观察者进行测试。下面提供测试方法供参考</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-java" data-lang="java"><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Test</span> <span style="color:#f92672">{</span>
    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">void</span> <span style="color:#a6e22e">main</span><span style="color:#f92672">(</span>String<span style="color:#f92672">[]</span> args<span style="color:#f92672">)</span> <span style="color:#f92672">{</span>
        WeatherData weatherData<span style="color:#f92672">=</span><span style="color:#66d9ef">new</span> WeatherData<span style="color:#f92672">();</span>
        <span style="color:#75715e">//观察者向主题注册
</span><span style="color:#75715e"></span>        CurrentConditionsDisplay currentConditionsDisplay<span style="color:#f92672">=</span><span style="color:#66d9ef">new</span> CurrentConditionsDisplay<span style="color:#f92672">(</span>weatherData<span style="color:#f92672">);</span>
        <span style="color:#75715e">//当气温站检测到新的气温后
</span><span style="color:#75715e"></span>        weatherData<span style="color:#f92672">.</span><span style="color:#a6e22e">setMeasurements</span><span style="color:#f92672">(</span>80<span style="color:#f92672">,</span>55<span style="color:#f92672">,</span>30<span style="color:#f92672">.</span><span style="color:#a6e22e">2f</span><span style="color:#f92672">);</span>
    <span style="color:#f92672">}</span>
<span style="color:#f92672">}</span>
</code></pre></div><h2 id="四适用场景">四、适用场景</h2>
<ul>
<li>
<p><strong>当一个对象状态的改变需要改变其他对象，或实际对象是事先未知的或动态变化的时，可使用观察者模式。</strong></p>
</li>
<li>
<p><strong>当应用中的一些对象必须观察其他对象时，可使用该模式。但仅能在有限时间内或特定情况下使用。</strong></p>
</li>
</ul>

</section>


    <footer class="article-footer">
    
    <section class="article-tags">
        
            <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
        
    </section>


    </footer>


    
</article>

    <aside class="related-contents--wrapper">
    
    
        <h2 class="section-title">Related contents</h2>
        <div class="related-contents">
            <div class="flex article-list--tile">
                
                    
<article class="has-image">
    <a href="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/">
        
        
            <div class="article-image">
                <img src="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1.72afca0035885f64fa98915b08659344_hu6c0eed8e37f4c0026f67918d61df758e_74484_250x150_fill_q75_box_smart1.jfif" 
                        width="250" 
                        height="150" 
                        loading="lazy" 
                        data-key="设计模式-策略模式" 
                        data-hash="md5-cq/KADWIX2T6mJFbCGWTRA==">
                
            </div>
        

        <div class="article-details">
            <h2 class="article-title">设计模式-策略模式</h2>
        </div>
    </a>
</article>
                
                    
<article class="has-image">
    <a href="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99/">
        
        
            <div class="article-image">
                <img src="/post/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99/%E8%AE%BE%E8%AE%A1.72afca0035885f64fa98915b08659344_hu6c0eed8e37f4c0026f67918d61df758e_74484_250x150_fill_q75_box_smart1.jfif" 
                        width="250" 
                        height="150" 
                        loading="lazy" 
                        data-key="设计模式-设计原则" 
                        data-hash="md5-cq/KADWIX2T6mJFbCGWTRA==">
                
            </div>
        

        <div class="article-details">
            <h2 class="article-title">设计模式-设计原则</h2>
        </div>
    </a>
</article>
                
            </div>
        </div>
    
</aside>

     
    
        
    

    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.2.1/jquery.min.js"></script>
        <script>
        function color_tags() {
            var colorArr = ["#428BCA", "#AEDCAE", "#ECA9A7", "#DA99FF", "#FFB380", "#D9B999"];
            $('.tagCloud-tags a').each(function () {
                try {
                    tagsColor = colorArr[Math.floor(Math.random() * colorArr.length)];
                    $(this).css("background", tagsColor); 
                }
                catch (err) { }
            });
        }

        $(document).ready(function () {
            color_tags()
        });
    </script>
    

    

    

    

    

    

    

    

    

    

    

    

    

    

    

    

    

    

    

    

<footer class="site-footer">
<span id="busuanzi_container_site_uv">
    本站总访问量<span id="busuanzi_value_site_uv"></span>次
</span>
    <section class="copyright">
        &copy; 
        
        2022zp妙妙屋·<i class="fas fa-bell"></i> <a id="days">0</a>Days<br>共叭叭了 3682字·共 16篇文章</br><span><p>
    </section>
    <div style="width:300px;margin:0 auto; padding:20px 0;">
    <a href="https://beian.miit.gov.cn/，" rel="external nofollow" target="_blank"><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 25px; color:#939393;">京ICP备2022000201号-1</p></a></span>
		 		<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11011102001825" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img src="/beian.png" style="float:left;"/><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;">京公网安备 11011102001825号</p></a>
	</div>
    <section class="powerby">
        Built with <a href="https://gohugo.io/" target="_blank" rel="noopener">Hugo</a> <br />
        Theme <b><a href="https://github.com/CaiJimmy/hugo-theme-stack" target="_blank" rel="noopener" data-version="3.5.0">Stack</a></b> designed by <a href="www.zpzp.vip" target="_blank" rel="noopener">ZP</a>
    </section>
</footer>



    
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    
    <div class="pswp__bg"></div>

    
    <div class="pswp__scroll-wrap">

        
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                
                
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div><script 
                src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"integrity="sha256-ePwmChbbvXbsO02lbM3HoHbSHTHFAeChekF1xKJdleo="crossorigin="anonymous"
                defer="true"
                >
            </script><script 
                src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"integrity="sha256-UKkzOn/w1mBxRmLLGrSeyB4e1xbrp4xylgAWb3M42pU="crossorigin="anonymous"
                defer="true"
                >
            </script><link 
                rel="stylesheet" 
                href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css"integrity="sha256-c0uckgykQ9v5k&#43;IqViZOZKc47Jn7KQil4/MP3ySA3F8="crossorigin="anonymous"
            ><link 
                rel="stylesheet" 
                href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.css"integrity="sha256-SBLU4vv6CA6lHsZ1XyTdhyjJxCjPif/TRkjnsyGAGnE="crossorigin="anonymous"
            >

            </main>
    
        <aside class="sidebar right-sidebar sticky">
            <section class="widget archives">
                <div class="widget-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-hash" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
  <path stroke="none" d="M0 0h24v24H0z"/>
  <line x1="5" y1="9" x2="19" y2="9" />
  <line x1="5" y1="15" x2="19" y2="15" />
  <line x1="11" y1="4" x2="7" y2="20" />
  <line x1="17" y1="4" x2="13" y2="20" />
</svg>



                </div>
                <h2 class="widget-title section-title">Table of contents</h2>
                
                <div class="widget--toc">
                    <nav id="TableOfContents">
  <ul>
    <li><a href="#一模式简介">一、模式简介</a></li>
    <li><a href="#二模式详解">二、模式详解</a></li>
    <li><a href="#三代码示例">三、代码示例</a>
      <ul>
        <li><a href="#自定义">自定义</a></li>
        <li><a href="#java内置">java内置</a></li>
        <li><a href="#代码示例总结">代码示例总结</a></li>
      </ul>
    </li>
    <li><a href="#四适用场景">四、适用场景</a></li>
  </ul>
</nav>
                </div>
            </section>
        </aside>
    

        </div>
        <script 
                src="https://cdn.jsdelivr.net/npm/node-vibrant@3.1.5/dist/vibrant.min.js"integrity="sha256-5NovOZc4iwiAWTYIFiIM7DxKUXKWvpVEuMEPLzcm5/g="crossorigin="anonymous"
                defer="false"
                >
            </script><script type="text/javascript" src="/ts/main.js" defer></script>
<script>
    (function () {
        const customFont = document.createElement('link');
        customFont.href = "https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap";

        customFont.type = "text/css";
        customFont.rel = "stylesheet";

        document.head.appendChild(customFont);
    }());
</script>

<script
    src="https://cdn.jsdelivr.net/gh/zhixuan2333/gh-blog@v0.1.0/js/ribbon.min.js"
    integrity="sha384-UEK8ZiP3VgFNP8KnKMKDmd4pAUAOJ59Y2Jo3ED2Z5qKQf6HLHovMxq7Beb9CLPUe"
    crossorigin="anonymous"
    size="300"
    alpha="0.6"
    zindex="-1"
    defer
></script>
<script
    src="https://cdn.jsdelivr.net/gh/zhixuan2333/gh-blog@v0.1.0/js/nprogress.min.js"
    integrity="sha384-bHDlAEUFxsRI7JfULv3DTpL2IXbbgn4JHQJibgo5iiXSK6Iu8muwqHANhun74Cqg"
    crossorigin="anonymous"
></script>
<link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/gh/zhixuan2333/gh-blog@v0.1.0/css/nprogress.css"
    integrity="sha384-KJyhr2syt5+4M9Pz5dipCvTrtvOmLk/olWVdfhAp858UCa64Ia5GFpTN7+G4BWpE"
    crossorigin="anonymous"
/>
<script src="/js/snow.js"></script>
<script>
    NProgress.start();
    document.addEventListener("readystatechange", () => {
        if (document.readyState === "interactive") NProgress.inc(0.8);
        if (document.readyState === "complete") NProgress.done();
    });
</script>

    </body>
</html>
